import { ref } from 'vue'
import type { SaveModel, TableModel } from "./interface";
import useBillId from "./useBillId";
import service from "../common/service";
import { getRdsUrl } from '@/hooks/rdsServices';

function useSaveBill(config ?: {
	uniqueKey ?: string,
	prefix?: string 
	table ?: TableModel,
	billName ?: string,
	method ?: string,
	billType ?: string
}) {
	const { prefix, uniqueKey, billName = uniqueKey, table, method = 'EnjoyBillSaveNew', billType} = config || {};
	const { createBillId } = useBillId({})
	const rdsUrl = getRdsUrl()

	const prexy = prefix || 'apiApi';
	const billIdRef = ref('');


	const saveBill = async (isAdd?:boolean,mainData ?: any, ...details : any[]) => {

		const billId = mainData.c_id || billIdRef.value;


		const model : SaveModel<any> = {
			TableName: table.main[0].tableName,
			PrimaryKeys: table.main[0].primaryKeys || ['c_tenant_id', 'c_id'],
			NewList: isAdd?[mainData]:[],
			ModifiedList: isAdd?[]:[mainData],
			DelList: [],
			ChildData: [],
			BillSet: {
				TableName: table.main[0].tableName,
				ColumnName: 'c_id',
				BillName: billName,
				BillIdKeyValue: {
					key: 'c_id',
					value: billId
				}
			}
		}

		table.detail?.forEach((item, index) => {
			const childData = details[index];
			if (childData && childData.length > 0) {
				model.ChildData.push({
					RelationName: item.tableName,
					ParentTableName: table.main[0].tableName,
					ChildTableName: item.tableName,
					ParentColumnNames: ['c_id'],
					ChildColumnNames: ['c_id'],
					ChildSaveModel: {
						TableName: item.tableName,
						PrimaryKeys: item.primaryKeys,
						NewList: childData[0].NewList??[],
						ModifiedList: childData[0].ModifiedList??[],
						DelList: childData[0].DelList??[]
					}
				})
			}
		});

		const idResult = !billId ? await createBillId(model.BillSet, mainData, billName) : { message: '' };
		if (idResult.message) {
			uni.showToast({
				duration: 3500,
				icon: 'none',
				title: idResult.message
			});
			return {
				HasException: true, Exception: { Message: idResult.message }
			}
		}
		return new Promise((resolve, reject) => {
		let request = {
			 url:rdsUrl[prexy],
			data: {
				UniqueKey: uniqueKey,
				MethodName: method,
				ObjectData: model,
				BillType: billType,
			},
		};
		service.request(request, (res) => {
			if (res && res.data) {
				if (!res.data.HasException) {
					console.log('enjoysave',res.data)
					 resolve(res.data.ObjectData);
				} else {
					uni.showToast({
						duration: 3500,
						icon: 'none',
						title: res.data.Exception.Message,
						mask: true,
					});
					reject(res.data.Exception.Message);
				}
			}
		}, () => {
			console.log('请求失败');
			reject('请求失败');
		});
		});
		

	}

	const createId = async (mainData) : Promise<string> => {
		if (billIdRef.value) return billIdRef.value;
		if (!mainData.c_id) {
			const billSet = {
				TableName: table.main[0].tableName,
				ColumnName: 'c_id',
				BillName: billName,
				BillIdKeyValue: {
					key: 'c_id',
					value: mainData.c_id
				}
			}
			const idResult = await createBillId(billSet, mainData, billName);
			if (idResult.message) {
				uni.showToast({
					duration: 3500,
					icon: 'none',
					title: idResult.message
				});
				return '';
			}
			billIdRef.value = idResult.billId;
			mainData.c_id = idResult.billId;
			return idResult.billId;
		}
		else {
			return mainData.c_id;
		}
	}

	return { save: saveBill, createId }
}

export default useSaveBill;